require 'digest/sha2'
class User < ActiveRecord::Base
  validates :studentId, :uniqueness => true
  validates :password, :confirmation => true
  attr_accessor :password_confirmation
  attr_reader :password
  validates :emailAddress, :password,:studentId, :presence => true
   validates :emailAddress, :format => { 
     :with => /^(|(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6})$/i
 }
  def User.authenticate(studentId, password)
    if user = find_by_studentId(studentId)
      if user.hashed_password == encrypt_password(password, user.salt)
      user
      end
    end
  end
  def User.encrypt_password(password, salt)
    Digest::SHA2.hexdigest(password + "wibble" + salt)
  end
# 'password' is a virtual attribute
  def password=(password)
    @password = password
     if password.present?
       generate_salt
       self.hashed_password = self.class.encrypt_password(password, salt)
     end
  end
  private
  def password_must_be_present
     errors.add(:password, "missing") unless hashed_password.present?
  end
  def generate_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
  

end